import { Body, Controller, Get, Patch, Post, Put } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { AuditLog, CurrentUserId, CurrentToken, Public } from '@nbase/nest-mods';
import { AUDIT_LOG_OPERATION_TYPE, type ILoginResponse, type IUserProfile, type IMenuTree } from '@nbase/shared';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';

/**
 * 认证控制器
 */
@ApiTags('认证')
@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  /**
   * 用户登录
   */
  @AuditLog({
    module: '认证',
    operationType: AUDIT_LOG_OPERATION_TYPE.LOGIN,
    description: '用户登录',
  })
  @ApiOperation({ summary: '用户登录' })
  @ApiResponse({
    status: 200,
    description: '登录成功',
    schema: {
      example: {
        accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
        tokenType: 'Bearer',
        expiresIn: 604800,
        user: {
          username: 'admin',
          nickname: '系统管理员',
          email: 'admin@example.com',
          mobile: '13800138000',
          avatar: 'https://example.com/avatar.jpg',
          deptId: null,
          status: 1,
          roles: ['admin'],
          permissions: ['*:*:*']
        }
      }
    }
  })
  @ApiResponse({ status: 401, description: '用户名或密码错误' })
  @Public()
  @Post('login')
  async login(@Body() loginDto: LoginDto): Promise<ILoginResponse> {
    return this.authService.login(loginDto);
  }

  /**
   * 用户登出
   */
  @AuditLog({
    module: '认证',
    operationType: AUDIT_LOG_OPERATION_TYPE.LOGOUT,
    description: '用户登出',
  })
  @ApiOperation({ summary: '用户登出' })
  @ApiResponse({ status: 200, description: '登出成功' })
  @ApiBearerAuth('JWT-auth')
  @Post('logout')
  async logout(@CurrentToken() token: string): Promise<void> {
    await this.authService.logout(token);
  }

  /**
   * 获取当前用户信息
   */
  @ApiOperation({ summary: '获取当前用户信息' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    schema: {
      example: {
        username: 'admin',
        nickname: '系统管理员',
        email: 'admin@example.com',
        mobile: '13800138000',
        avatar: 'https://example.com/avatar.jpg',
        deptId: null,
        status: 1,
        roles: ['admin'],
        permissions: ['*:*:*']
      }
    }
  })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiBearerAuth('JWT-auth')
  @Get('profile')
  async getProfile(@CurrentUserId() userId: string): Promise<IUserProfile> {
    return this.authService.getProfile(userId);
  }

  /**
   * 修改密码
   */
  @AuditLog({
    module: '认证',
    operationType: AUDIT_LOG_OPERATION_TYPE.UPDATE,
    description: '修改密码',
  })
  @ApiOperation({ summary: '修改密码' })
  @ApiResponse({ status: 200, description: '修改成功' })
  @ApiResponse({ status: 400, description: '旧密码不正确' })
  @ApiBearerAuth('JWT-auth')
  @Put('password')
  async changePassword(
    @CurrentUserId() userId: string,
    @Body() dto: ChangePasswordDto
  ): Promise<void> {
    return this.authService.changePassword(userId, dto);
  }

  /**
   * 更新个人信息
   */
  @AuditLog({
    module: '认证',
    operationType: AUDIT_LOG_OPERATION_TYPE.UPDATE,
    description: '更新个人信息',
  })
  @ApiOperation({ summary: '更新个人信息' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @ApiBearerAuth('JWT-auth')
  @Patch('profile')
  async updateProfile(
    @CurrentUserId() userId: string,
    @Body() dto: UpdateProfileDto
  ): Promise<IUserProfile> {
    return this.authService.updateProfile(userId, dto);
  }

  /**
   * 获取当前用户的菜单树（用于动态路由）
   */
  @ApiOperation({ summary: '获取当前用户的菜单树' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    schema: {
      example: [
        {
          id: '1',
          name: '系统管理',
          permission: 'system',
          type: 1,
          sort: 1,
          parentId: null,
          path: '/system',
          icon: 'SettingOutlined',
          component: null,
          visible: true,
          keepAlive: false,
          children: [
            {
              id: '2',
              name: '用户管理',
              permission: 'system:user',
              type: 1,
              sort: 1,
              parentId: '1',
              path: '/system/user',
              icon: 'TeamOutlined',
              component: 'System/User',
              visible: true,
              keepAlive: true,
              children: []
            }
          ]
        }
      ]
    }
  })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiBearerAuth('JWT-auth')
  @Get('menus')
  async getUserMenus(@CurrentUserId() userId: string): Promise<IMenuTree[]> {
    return this.authService.getUserMenus(userId);
  }

}

